package com.zu.commu.remote.threads;

import com.zu.commu.remote.handle.HandleGPRS;
import com.zu.commu.remote.session.Session;
import org.apache.log4j.Logger;

public class ReadThread extends Thread
{
  Logger log = Logger.getLogger("com.automic.commu.remote.threads.ReadThread");
  private boolean canRead;
  public boolean isCanRead() {
	return canRead;
}
private Session se;
  private int num;

  public ReadThread(int num)
  {
    this.canRead = false;
    this.num = num;
    this.setName("myThread"+num);
  }

  public void setReadSession(Session se)
  {
    synchronized (this) {
      this.se = se;
      this.canRead = true;
      log.debug("---线程：" + this.getName() + "--start notify");
      this.notify();
    }
  }

	public void run() {
		while (true) {
			synchronized (this) {
				while (!this.canRead) {
					try {
						log.debug("---线程：" + this.getName() + "--start wait");
						wait();
						log.debug("---线程：" + this.getName() + "--End wait");
					} catch (Exception e) {

						log.error("线程 " + this.num + " 等待可读信号时发生等待异常", e);
						if (!this.canRead)
							continue;
						ReadThreadManager.instance().freeThread(this.num, this);
						this.canRead = false;
					}
				}
				byte[] bytes = (byte[]) null;
				boolean isException = false;
				try {
					bytes = this.se.read();
				} catch (Exception e) {
					log.error("线程 " + this.getName() + "从GPRSID:"
							+ this.se.getAttribute("gprsId") + "读取数据发生异常，"
							+ e.getMessage());
					isException = true;
				} finally {
					try {
						if (!isException && bytes != null && bytes.length > 0) {
							new HandleGPRS(this.se).processData(this.num, bytes);
						} else {
							log.debug("线程：" + this.getName()
									+ "没有动作：isException：" + isException
									+ "-bytes:" + bytes);
						}
					} catch (Exception localException2) {
						log.error("线程" + this.getName() + "processData过程中出现错误"
								+ localException2.getMessage());
					} finally {
						isException = false;
						this.canRead = false;
						ReadThreadManager.instance().freeThread(this.num, this);
					}
				}
			}
		}
	}
  public void destroy()
  {
	this.canRead = false;
    this.se = null;
    log.debug("---线程：" + this.getName() + "被清理。。。");
  }
}